<template>
	<div>
		<a-card title="基本信息" class="form-card">
			<a-form ref="formRef" :model="formData" layout="vertical" :rules="formRules">
				<a-form-item label="姓名" name="fullName">
					<a-input v-model:value="formData.fullName" placeholder="请输入姓名" />
				</a-form-item>
				<!-- 身份证号码 -->
				<a-form-item label="身份证号码" name="idCard">
					<a-input v-model:value="formData.idCard" placeholder="请输入身份证号码" @blur="handleIdCardInput" />
				</a-form-item>
				<a-form-item label="性别" name="gender">
					<a-select v-model:value="formData.gender" placeholder="请选择性别" :options="genderOptions" />
				</a-form-item>
				<a-form-item label="出生日期" name="birthDate">
					<a-date-picker v-model:value="formData.birthDate" placeholder="请选择出生日期" style="width: 100%" />
				</a-form-item>
				<a-form-item label="民族" name="ethnicity">
					<a-select v-model:value="formData.ethnicity" placeholder="请选择民族" :options="nationOptions" />
				</a-form-item>
				<a-form-item label="政治面貌" name="politicalStatus">
					<a-select v-model:value="formData.politicalStatus" placeholder="请选择政治面貌">
						<a-select-option value="群众">群众</a-select-option>
						<a-select-option value="团员">团员</a-select-option>
						<a-select-option value="党员">党员</a-select-option>
						<a-select-option value="预备党员">预备党员</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="籍贯" name="nativePlace">
					<a-input v-model:value="formData.nativePlace" placeholder="请输入籍贯" />
				</a-form-item>
				<a-form-item label="婚姻状况" name="maritalStatus">
					<a-select v-model:value="formData.maritalStatus" placeholder="请选择婚姻状况">
						<a-select-option value="未婚">未婚</a-select-option>
						<a-select-option value="已婚">已婚</a-select-option>
						<a-select-option value="离异">离异</a-select-option>
						<a-select-option value="丧偶">丧偶</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="身份证照片" name="idCardImage">
					<a-upload
						v-model:file-list="idCardImageList"
						list-type="picture-card"
						accept="image/jpeg,image/png"
						:multiple="true"
						:before-upload="beforeUpload"
						@change="handleChange"
						@preview="handlePreview"
						:showUploadList="{ showRemoveIcon: false }"
					>
						<div class="upload-btn">
							<plus-outlined />
							<div style="margin-top: 8px">上传照片</div>
						</div>
					</a-upload>
					<a-button @click="clearAllImages">清空</a-button>
					<div class="photo-count">已上传 {{ idCardImageList.length }} 张照片</div>
				</a-form-item>
			</a-form>
		</a-card>
	</div>
</template>
<script setup>
	import { reactive, ref, watch } from 'vue'
	import tool from '@/utils/tool'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import { message } from 'ant-design-vue'
	import dayjs from 'dayjs'
	import { required } from '@/utils/formRules'
	import Promise from 'lodash-es/_Promise'
	import onboardingRegistryApi from '@/api/hrms/onboarding/registry/onboardingRegistryApi'

	// 父组件传入的数据
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	const nationOptions = tool.dictList('NATION')
	const genderOptions = tool.dictList('GENDER')
	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'

	// 表单引用
	const formRef = ref()

	// 预览相关
	const previewImageSrc = ref('')
	const previewVisible = ref(false)

	// 表单数据
	const formData = reactive({
		fullName: '',
		idCard: '',
		gender: undefined,
		birthDate: undefined,
		ethnicity: '汉族',
		politicalStatus: undefined,
		nativePlace: '',
		maritalStatus: undefined,
		idCardImage: undefined
	})

	const formRules = {
		fullName: [required('请输入姓名')],
		idCard: [required('请输入身份证号码')],
		gender: [required('请选择性别')],
		birthDate: [required('请选择出生日期')],
		ethnicity: [required('请选择民族')],
		politicalStatus: [required('请选择政治面貌')],
		nativePlace: [required('请输入籍贯')],
		maritalStatus: [required('请选择婚姻状况')],
		idCardImage: [
			{
				required: true,
				validator: (rule, value) => {
					if (idCardImageList.value.length === 0) {
						return Promise.reject('请上传身份证照片')
					} else {
						return Promise.resolve()
					}
				},
				trigger: 'change'
			}
		]
	}

	//身份证照片
	const idCardImageList = ref([])

	// 监听父组件传入数据
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal) {
				Object.keys(newVal).forEach((key) => {
					if (key in formData) {
						// 特别处理 birthDate 字段，确保是 dayjs 对象
						if (key === 'birthDate' && newVal[key]) {
							formData[key] = dayjs(newVal[key])
						} else if (key === 'idCardImage' && newVal[key]) {
							const fileNames = newVal[key].split(',')
							idCardImageList.value = fileNames.map((fileName, index) => ({
								uid: -index,
								name: fileName,
								status: 'done',
								url: `${jdOssBaseUrl}${fileName}`
							}))
						} else {
							formData[key] = newVal[key]
						}
					}
				})
			}
		},
		{ immediate: true, deep: true }
	)

	// 处理身份证号码输入变化
	const handleIdCardInput = () => {
		const idCard = formData.idCard
		if (!idCard) return
		const result = validateAndExtractIdCardInfo(idCard)
		if (result.valid) {
			formData.gender = result.gender
			formData.birthDate = dayjs(result.birthDate)
			message.success('身份证号码验证通过，已自动填充性别和出生日期')
		} else {
			message.error(result.message)
		}
	}

	// 身份证号码校验和信息提取
	const validateAndExtractIdCardInfo = (idCard) => {
		if (!idCard || idCard.length !== 18) {
			return { valid: false, message: '身份证号码长度不正确' }
		}
		// 省份代码校验
		const provinceCode = idCard.substring(0, 2)
		const validProvinces = [
			'11',
			'12',
			'13',
			'14',
			'15',
			'21',
			'22',
			'23',
			'31',
			'32',
			'33',
			'34',
			'35',
			'36',
			'37',
			'41',
			'42',
			'43',
			'44',
			'45',
			'46',
			'50',
			'51',
			'52',
			'53',
			'54',
			'61',
			'62',
			'63',
			'64',
			'65',
			'71',
			'81',
			'82'
		]
		if (!validProvinces.includes(provinceCode)) {
			return { valid: false, message: '身份证号码省份代码不正确' }
		}
		// 出生日期校验
		const birthYear = idCard.substring(6, 10)
		const birthMonth = idCard.substring(10, 12)
		const birthDay = idCard.substring(12, 14)
		const birthDateStr = `${birthYear}-${birthMonth}-${birthDay}`
		const birthDate = dayjs(birthDateStr, 'YYYY-MM-DD', true)
		if (!birthDate.isValid()) {
			return { valid: false, message: '身份证号码出生日期不正确' }
		}
		// 校验码校验
		const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
		const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
		let sum = 0
		for (let i = 0; i < 17; i++) {
			sum += parseInt(idCard.charAt(i)) * weightFactors[i]
		}
		const mod = sum % 11
		const checkCode = checkCodes[mod]
		if (checkCode !== idCard.charAt(17).toUpperCase()) {
			return { valid: false, message: '身份证号码校验码不正确' }
		}
		// 提取性别信息 (第17位奇数为男，偶数为女)
		const genderCode = parseInt(idCard.charAt(16))
		const gender = genderCode % 2 === 0 ? '女' : '男'
		return {
			valid: true,
			gender: gender,
			birthDate: birthDateStr
		}
	}

	const beforeUpload = (file) => {
		idCardImageList.value = idCardImageList.value.filter((item) => item.originFileObj)
		return false
	}

	const handleChange = ({ fileList: newFileList }) => {
		// 去重处理
		const uniqueFiles = []
		const seen = new Set()
		newFileList.forEach((file) => {
			const key = file.uid || file.name
			if (!seen.has(key)) {
				seen.add(key)
				uniqueFiles.push(file)
			}
		})
		idCardImageList.value = uniqueFiles
	}

	const handlePreview = (file) => {
		previewImageSrc.value = file.url || file.thumbUrl
		previewVisible.value = true
	}

	const clearAllImages = () => {
		idCardImageList.value = []
		nextTick(() => {
			formRef.value?.validateFields(['idCardImage'])
		})
	}

	// 保存数据方法（供父组件调用）
	async function saveData() {
		await formRef.value.validateFields()
		formData.birthDate = formData.birthDate ? formData.birthDate.format('YYYY-MM-DD') : null
		const submitData = new FormData()
		submitData.append(
			'onboardingRegistryEditBo',
			new Blob([JSON.stringify({ basicEditBo: formData })], {
				type: 'application/json'
			})
		)
		if (idCardImageList.value.length > 0) {
			idCardImageList.value.forEach((file) => {
				if (file.originFileObj) {
					submitData.append('multipartFileList', file.originFileObj)
				}
			})
		}
		await onboardingRegistryApi.updateRegistryInfo(props.modelValue.id, submitData)
		message.success('基本信息保存成功')
	}

	// 暴露保存数据方法给父组件调用
	defineExpose({
		saveData
	})
</script>

<style scoped>
	.form-card {
		margin-bottom: 16px;
		border-radius: 8px;
	}

	.form-card :deep(.ant-card-head) {
		background-color: #fafafa;
		border-radius: 8px 8px 0 0;
	}
</style>
